<template>
  <div v-loading="handleLoading">
    <el-form
      ref="handleForm"
      :model="handleForm"
      :rules="handleRules"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="name" label="部门简称">
            <el-input
              v-model="handleForm.name"
              placeholder="请输入部门简称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="cname" label="部门全称">
            <el-input
              v-model="handleForm.cname"
              placeholder="请输入部门全称"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item prop="deptpath" label="部门地址">
        <el-input
          v-model="handleForm.deptpath"
          placeholder="请输入部门地址"
          @blur="queryLocation"
        />
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="coordinate" label="部门坐标">
            <el-input
              v-model="handleForm.coordinate"
              placeholder="请输入部门坐标"
            >
              <i slot="suffix" style="cursor: pointer;" title="坐标拾取" class="el-input__icon el-icon-s-promotion" @click="getPosition" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="depttel" label="部门电话(电话号码格式xx-xx)">
            <el-input
              v-model="handleForm.depttel"
              placeholder="请输入部门电话"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="btns btn-right-container">
      <el-button type="normal" size="medium" @click="$emit('closeDialog', false)">
        关闭
      </el-button>
      <el-button type="primary" size="medium" @click="saveInfo">
        保存
      </el-button>
    </div>
  </div>
</template>
<script>
import { getCoord } from '@/utils/tool'
import { addDept, editDept } from '@/api/dept'
import { isPhoneOrMobile } from '@/utils/validate'
export default {
  name: 'DeptHandle',
  props: {
    action: {
      type: String,
      default: 'add'
    },
    formData: {
      type: Object,
      default: () => ({})
    },
    pid: {
      type: [Number, String],
      default: ''
    }
  },
  data() {
    const validPhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('部门电话不能为空'))
      } else if (isPhoneOrMobile(value)) {
        callback()
      } else {
        callback(new Error('电话号码格式错误'))
      }
    }
    return {
      handleLoading: false,
      handleForm: {
        name: '',
        cname: '',
        deptpath: '',
        coordinate: '',
        depttel: ''
      },
      handleRules: {
        name: [{
          required: true, message: '部门简称不能为空', trigger: 'blur'
        }],
        cname: [{
          required: true, message: '部门全称不能为空', trigger: 'blur'
        }],
        deptpath: [{
          required: true, message: '部门地址不能为空', trigger: 'blur'
        }],
        coordinate: [{
          required: false, message: '部门坐标不能为空', trigger: 'blur'
        }],
        depttel: [{
          required: true, validator: validPhone, trigger: 'blur'
        }]
      }
    }
  },
  created() {
    if (this.action == 'edit') {
      this.initHandleForm()
    }
  },
  methods: {
    saveInfo() {
      this.$refs.handleForm.validate(valid => {
        if (!valid) return
        this.handleLoading = true
        let fn = addDept
        const param = {
          ...this.handleForm,
          enabled: 1,
          pid: this.pid
        }
        if (this.action == 'edit') {
          fn = editDept
          param.id = this.formData.id
        }
        fn(param).then(() => {
          this.$message({
            message: `${this.action == 'add' ? '新增' : '修改'}成功`,
            type: 'success'
          })
          this.$emit('closeDialog', true)
        }).catch(() => {
          this.$message({
            message: `${this.action == 'add' ? '新增' : '修改'}失败`,
            type: 'error'
          })
        }).finally(() => {
          this.handleLoading = false
        })
      })
    },
    initHandleForm() {
      Object.keys(this.handleForm).forEach(key => {
        this.handleForm[key] = this.formData[key]
      })
      this.$nextTick(() => {
        this.$refs.handleForm.clearValidate()
      })
    },
    getPosition() {
      window.open('https://lbs.amap.com/console/show/picker', '坐标选取', 'height=620, width=920,toolbar=no, top=100, left=120')
    },
    // 地址输入框失去焦点后自动获取坐标
    async queryLocation() {
      if (!this.handleForm.deptpath || /^\s+$/g.test(this.handleForm.deptpath)) {
        return false
      }
      this.handleLoading = true
      let coord = ''
      try {
        coord = await getCoord(this.handleForm.deptpath)
        this.handleForm.coordinate = coord
        this.handleLoading = false
      } catch (err) {
        this.handleLoading = false
        this.$message({
          message: err,
          type: 'error'
        })
      }
    }
  }
}
</script>
